import {
  deleteArticleCollectRecordFile,
  findArticleCollectRecord,
  updateArticleToFavoriteById,
  updatefavoritesInfo,
} from '@/services/articles';
import { createArticleCollectRecordFile, findArticleCollectRecordFile } from '@/services/user';
import useRequest from '@ahooksjs/use-request';
import {
  DragOutlined,
  FolderOutlined,
  FormOutlined,
  PlusCircleOutlined,
  QuestionCircleOutlined,
} from '@ant-design/icons';
import {
  ModalForm,
  ProFormRadio,
  ProFormSelect,
  ProFormSwitch,
  ProFormText,
  ProFormTextArea,
} from '@ant-design/pro-components';
import { Button, Checkbox, Input, message, Pagination, Select, Spin, Tabs, Tooltip } from 'antd';
import classNames from 'classnames';
import { useEffect, useMemo, useState } from 'react';
import styles from './index.less';

const { Option } = Select;
const { Search } = Input;
const pagination = {
  pageSize: 10,
  current: 1,
};
type Props = {};
type SearchType = 'articleTitle' | 'author';
type CollectListT = USER.ArticleCollectT & {
  isActivate?: boolean;
  isDragenter?: boolean;
};

const Index: React.FC<Props> = () => {
  const [collectList, setCollectList] = useState<CollectListT[]>([]);
  const [nameIsEdit, setNameIsEdit] = useState<boolean>(false);
  const [articleList, setArticleList] = useState<COMMON.QueryListData<FAVORITES.FavoritesQT>>();
  const [dragItem, setDragItem] = useState<FAVORITES.FavoritesQT>();
  const [searchType, setSearchType] = useState<SearchType>('articleTitle');
  // 已选择的文章列表
  const [articleChecked, setArticleChecked] = useState<number[]>([]);
  // 收藏夹激活项
  const [activateFavorite, setActivateFavorite] = useState<USER.ArticleCollectT>();

  // 根据收藏夹id获取收藏夹内容
  const { run: findArticleCollectRecordRun, loading: findArticleCollectRecordLoding } = useRequest(
    findArticleCollectRecord,
    {
      manual: true,
      onSuccess(res) {
        if (res.code === 200) {
          setArticleList(res.data);
        }
      },
    },
  );
  // 获取收藏夹列表
  const { run: findArticleCollectRecordFileRun, loading: findArticleCollectRecordFileLoading } =
    useRequest(findArticleCollectRecordFile, {
      manual: true,
      onSuccess(res) {
        const { code, message: errorMessage, data } = res;
        if (code !== 200) message.error(errorMessage);
        const index = data.findIndex(
          (item) =>
            activateFavorite?.articleCollectRecordFileId === item.articleCollectRecordFileId,
        );
        if (index !== -1) {
          setActivateFavorite(data[index]);
        } else {
          setActivateFavorite(data[0]);
        }
        setCollectList(data);
      },
    });

  // 拖拽结束
  const blogItemDragStart = (val: FAVORITES.FavoritesQT) => {
    setDragItem(val);
  };

  // 拖拽过程
  const dragOverHandler = (e: any) => {
    e.preventDefault();
  };

  // 拖拽放到目标下
  const dragDropHandler = async (val: USER.ArticleCollectT) => {
    const { code, message: errMsg } = await updateArticleToFavoriteById({
      articleIds: [dragItem?.article.articleId],
      endArticleCollectRecordFileId: val.articleCollectRecordFileId,
    });
    if (code !== 200) return message.error(errMsg);
    setDragItem(undefined);
    await findArticleCollectRecordFileRun();
  };
  // 拖拽放下
  const dragEnd = () => {
    const newDate = collectList.map((item) => {
      return {
        ...item,
        isDragenter: false,
      };
    });
    setCollectList([...newDate]);
  };

  // 批量移动
  const batchMoveHandler = async (values: { endArticleCollectRecordFileId: number }) => {
    if (articleChecked.length === 0) {
      message.warning('请选择要移动的文章');
      return false;
    }
    const { code, message: errMsg } = await updateArticleToFavoriteById({
      articleIds: articleChecked,
      endArticleCollectRecordFileId: values.endArticleCollectRecordFileId,
    });
    if (code !== 200) {
      message.error(errMsg);
      return false;
    }
    setDragItem(undefined);
    await findArticleCollectRecordFileRun();
    return true;
  };

  // 文章列表
  const blogListRender = () => {
    return (
      <Checkbox.Group style={{ width: '100%' }} onChange={(e: any[]) => setArticleChecked(e)}>
        {articleList?.records?.map((item) => {
          return (
            <div
              draggable="true"
              onDragStart={() => blogItemDragStart(item)}
              onDragEnd={dragEnd}
              key={item.articleCollectRecordId}
            >
              <Checkbox value={item.article.articleId} className={styles.blogItem}>
                <div className={styles.blogTitle}>{item.article.articleTitle}</div>
              </Checkbox>
            </div>
          );
        })}
      </Checkbox.Group>
    );
  };

  // tabs列表
  const items = new Array(3).fill(null).map((_, i) => {
    const id = String(i + 1);
    return {
      label: `全部${id}`,
      key: id,
      children: blogListRender(),
    };
  });

  const onSearch = (e: string) => {
    findArticleCollectRecordRun({
      ...pagination,
      articleCollectRecordFileId: activateFavorite?.articleCollectRecordFileId,
      [searchType]: e,
    });
  };

  const operations = () => {
    return (
      <Input.Group compact className={styles.searchWrapper}>
        <Select value={searchType} onChange={setSearchType}>
          <Option value="articleTitle">标题</Option>
          <Option value="author">作者</Option>
        </Select>
        <Search
          onSearch={onSearch}
          placeholder="请输入搜索内容"
          loading={findArticleCollectRecordLoding}
        />
      </Input.Group>
    );
  };

  // 移入选中
  const dragEnterHandler = (val: number) => {
    const newDate: CollectListT[] = collectList.map((item) => {
      if (item.articleCollectRecordFileId === val) {
        item.isDragenter = true;
      } else {
        item.isDragenter = false;
      }
      return item;
    });
    setCollectList([...newDate]);
  };

  // 收藏夹信息发生改变
  const changeFavoritesInfo = async (val: ARTICLEAPI.UpdateFavoriteInfo) => {
    if (activateFavorite?.articleCollectRecordFileName !== val.articleCollectRecordFileName) {
      const { code, message: errorMsg } = await updatefavoritesInfo({
        articleCollectRecordFileId: activateFavorite?.articleCollectRecordFileId,
        ...val,
      });
      if (code === 200) {
        findArticleCollectRecordFileRun();
        setNameIsEdit(false);
      } else {
        message.error(errorMsg);
      }
    }
  };

  const collectEnum = useMemo(() => {
    return collectList.map((item) => {
      return {
        value: item.articleCollectRecordFileId,
        label: item.articleCollectRecordFileName,
        disabled: item.articleCollectRecordFileId === activateFavorite?.articleCollectRecordFileId,
      };
    });
  }, [collectList]);

  useEffect(() => {
    if (activateFavorite?.articleCollectRecordFileId) {
      findArticleCollectRecordRun({
        ...pagination,
        articleCollectRecordFileId: activateFavorite.articleCollectRecordFileId,
      });
    }
  }, [activateFavorite, findArticleCollectRecordRun]);

  useEffect(() => {
    findArticleCollectRecordFileRun();
  }, []);

  return (
    <div className={styles.myCollectWrapper}>
      <div className={styles.menuListWrapper}>
        <Spin
          tip="Loading..."
          spinning={findArticleCollectRecordFileLoading || findArticleCollectRecordLoding}
          style={{ height: '100%' }}
        >
          {collectList?.map((item) => {
            return (
              <div
                onDragOver={dragOverHandler}
                onDragEnter={() => {
                  dragEnterHandler(item.articleCollectRecordFileId);
                }}
                onDrop={() => dragDropHandler(item)}
                className={classNames(
                  styles.menuItem,
                  item.isDragenter ? styles.dragenterMenuItem : null,
                  item.articleCollectRecordFileId === activateFavorite?.articleCollectRecordFileId
                    ? styles.activateMenuItem
                    : null,
                )}
                key={item.articleCollectRecordFileId}
                onClick={() => setActivateFavorite(item)}
              >
                <div className={styles.left}>
                  <FolderOutlined className={styles.menuIcon} />
                  <div className={styles.menuTitle}>{item.articleCollectRecordFileName}</div>
                </div>
                <div className={styles.collectCount}>
                  <FolderOutlined className={styles.countIcon} />
                  {item.collectCount}
                </div>
              </div>
            );
          })}
        </Spin>
      </div>
      <div className={styles.rightContentWrapper}>
        <Spin
          tip="Loading..."
          spinning={findArticleCollectRecordFileLoading || findArticleCollectRecordLoding}
          style={{ height: '100%' }}
        >
          <div className={styles.collectTitle}>
            <div className={styles.favoriteNameWrapper}>
              {nameIsEdit ? (
                <Input
                  onBlur={(e) =>
                    changeFavoritesInfo({
                      articleCollectRecordFileName: e.target.value,
                    })
                  }
                  defaultValue={activateFavorite?.articleCollectRecordFileName}
                  placeholder="请输入文件夹名称"
                />
              ) : (
                activateFavorite?.articleCollectRecordFileName
              )}
              <FormOutlined
                className={styles.editCollectTitle}
                onClick={() => setNameIsEdit(true)}
              />
            </div>
            <Button type="dashed" ghost icon={<DragOutlined />} shape="round" danger>
              文章支持直接拖拽到其他文件夹下完成切换文件夹
            </Button>
          </div>
          <div className={styles.operates}>
            <ModalForm<{
              articleCollectRecordFileName: string;
              description: string;
              privateFlag: boolean;
              default: boolean;
            }>
              width="500px"
              layout="horizontal"
              title="新增收藏夹"
              trigger={
                <a className={styles.item}>
                  新增收藏夹
                  <PlusCircleOutlined style={{ marginLeft: '6px' }} />
                </a>
              }
              modalProps={{
                destroyOnClose: true,
                onCancel: () => console.log('run'),
              }}
              onFinish={async (values: any) => {
                values.privateFlag = values.privateFlag ? 1 : 0;
                const { code, message: errorMessage } = await createArticleCollectRecordFile(
                  values,
                );
                if (code === 200) {
                  message.success('创建成功');
                  findArticleCollectRecordFileRun();
                } else {
                  message.error(errorMessage);
                }
                return true;
              }}
            >
              <ProFormText
                formItemProps={{
                  rules: [
                    { required: true, message: '收藏夹名称必填' },
                    { max: 15, message: '名称最大长度为15' },
                  ],
                }}
                fieldProps={{ maxLength: 15, showCount: true }}
                name="articleCollectRecordFileName"
                placeholder="收藏夹名称"
              />
              <ProFormTextArea
                fieldProps={{ maxLength: 200, showCount: true }}
                name="description"
                placeholder="收藏夹描述(非必填)"
              />
              <ProFormSwitch
                colon={false}
                labelCol={{ span: 3 }}
                wrapperCol={{ span: 2, offset: 19 }}
                labelAlign="right"
                label="私密"
                tooltip="仅自己可见"
                name="privateFlag"
              />
              <ProFormSwitch
                colon={false}
                labelCol={{ span: 3 }}
                wrapperCol={{ span: 2, offset: 19 }}
                label="默认"
                tooltip="收藏文章是默认的收藏位置"
                name="default"
              />
            </ModalForm>
            <ModalForm<{
              delType: string;
            }>
              width="500px"
              title="删除收藏夹"
              trigger={<a className={styles.item}>删除收藏夹</a>}
              modalProps={{
                destroyOnClose: true,
                onCancel: () => console.log('run'),
              }}
              onFinish={async (values: any) => {
                console.log(values);
                if (values.delType == 'del' && activateFavorite) {
                  const { code, message: errMsg } = await deleteArticleCollectRecordFile(
                    activateFavorite.articleCollectRecordFileId,
                  );
                  if (code !== 200) {
                    message.error(errMsg);
                    return false;
                  }
                  findArticleCollectRecordFileRun();
                }
                return true;
              }}
            >
              <div className={styles.modalSubTitle}>收藏夹的内容移动到</div>
              <ProFormRadio.Group
                name="delType"
                layout="vertical"
                options={[
                  {
                    label: (
                      <ProFormSelect
                        style={{ width: '260px' }}
                        options={collectEnum}
                        name="useMode"
                      />
                    ),
                    value: 'move',
                    style: { display: 'flex' },
                  },
                  {
                    label: '一并删除(删除操作不可恢复)',
                    value: 'del',
                  },
                ]}
              />
            </ModalForm>
            <ModalForm<{
              endArticleCollectRecordFileId: number;
            }>
              width="500px"
              title="批量移动"
              trigger={<a className={styles.item}>批量移动</a>}
              modalProps={{
                destroyOnClose: true,
                onCancel: () => console.log('run'),
              }}
              onFinish={batchMoveHandler}
            >
              <div className={styles.modalSubTitle}>收藏夹的内容移动到</div>
              <ProFormSelect
                style={{ width: '260px' }}
                options={collectEnum}
                name="endArticleCollectRecordFileId"
              />
            </ModalForm>
            <a
              className={styles.item}
              onClick={() =>
                changeFavoritesInfo({
                  privateFlag: activateFavorite?.privateFlag ? 0 : 1,
                })
              }
            >
              <span style={{ marginRight: '6px' }}>
                {activateFavorite?.privateFlag ? '设为公开' : '设为私密'}
              </span>
              <Tooltip
                title={
                  activateFavorite?.privateFlag ? '当前收藏夹为公开状态' : '当前收藏夹外人不可见'
                }
                color="blue"
              >
                <QuestionCircleOutlined />
              </Tooltip>
            </a>
          </div>
          <Tabs tabBarExtraContent={operations()} items={items} />
          <div className={styles.paginationWrapper}>
            <Pagination
              hideOnSinglePage={true}
              defaultCurrent={articleList?.current || 1}
              total={articleList?.total || 0}
            />
          </div>
        </Spin>
      </div>
    </div>
  );
};
export default Index;
